<template>
  <div class="Diary">
    <Nav></Nav>
    <Leader gameName="五子棋" ref="lea"></Leader>
    <div class="diary-main">
      <div class="nav">
        人机五子棋 ,注意刷新不保存哦~
      </div>
      <div class="container">
        <div>
<!--          <canvas id="chess" width="450px" height="450px"></canvas>-->
          <canvas
              id="canvas"
              ref="canvas"
              width="800"
              disabled="true"
              height="600"
              @mousedown="canvasDown($event)"
          ></canvas>
          <div id="screen"></div>
        </div>
      </div>
    </div>
  </div>

</template>
<script defer=true>
import Nav from "../../components/Nav";
import Leader from "../../components/Leader";
import request from "../../api";

import "../../assets/js/phaser.min.js";
// import initGame from "../../assets/js/script.js";
// import  from "@/assets/js/dateformat";
const gamestatestx = require("../../assets/js/catch-the-cat.js");



export default {
  name: "goBang",
  components: { Nav, Leader },
  data() {
    return {
      context: {},
      me:true,
      over : false,
      location: {
        x:"",
        y:"",
        color:""
      },
      chessBoard:[],
      game: "",
      gamestate: "",
      userId: "",
      record: "未登录",
      setinterval1: 0,
      isWhite: -1,
      websock: {},

      chess:{},
    };
  },
  watch: {

  },
  methods: {
    initDraw() {
      for (let i = 0; i < 15; i++) {
        this.chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
          this.chessBoard[i][j] = 0;
        }
      }

      const canvas = document.querySelector('#canvas');
      this.context = canvas.getContext('2d');
      this.context.strokeStyle = "#0A0A0A";
      // 背景图片
      let logo = new Image();
      logo.src = require("./chess.jpg");
      var context=this.context;
      logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        // 绘制棋盘网格
        for (let i = 0; i < 15; i++) {
          context.moveTo(15 + i * 30, 15);
          context.lineTo(15 + i * 30, 430);
          context.stroke();
          context.moveTo(15, 15 + i * 30);
          context.lineTo(435, 15 + i * 30);
          context.stroke();
        }
      }

    },
    //棋盘点击事件
    canvasDown(e) {
      if (this.over) {
        return;
      }
      if (!this.me) {
        return;
      }
      let x = e.offsetX;
      let y = e.offsetY;
      // 注意, 横坐标是列, 纵坐标是行

      this.location.x = Math.floor(x / 30);
      this.location.y = Math.floor(y / 30);
      this.location.color = 0;
      console.log(this.chessBoard[this.location.y][this.location.x]);
      if (this.chessBoard[this.location.y ][this.location.x] == 0) {
        // TODO 发送坐标给服务器, 服务器要返回结果
        this.websock.send(JSON.stringify(this.location));
        this.oneStep(this.location.x, this.location.y, this.isWhite);
        this.chessBoard[this.location.y ][this.location.x] = 1;
      }
    },

    //渲染棋子
    oneStep(i, j, isWhite) {
      this.context.beginPath();
      this.context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
      this.context.closePath();
      var gradient = this.context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
      if (isWhite===-1) {
        gradient.addColorStop(0, "#0A0A0A");
        gradient.addColorStop(1, "#636766");
      } else {
        gradient.addColorStop(0, "#D1D1D1");
        gradient.addColorStop(1, "#F9F9F9");
      }
      this.context.fillStyle = gradient;
      this.context.fill();
    },

    socketInit: function () {
      var user=  this.$store.state.user;
      if (JSON.stringify(user) !== "{}" && JSON.stringify(user)!==undefined) {
      //已经登陆了
        this.userId =user.id;
      }else{
        //没有登陆，随机一个
        this.userId=-Math.floor(Math.random() * 1000000);
      }
      console.log(this.userId);
      const hh = window.location.href
      let url;
      if (hh.indexOf('https') > -1) {
         url = "wss://"+this.$config.websocketurl+"/pveGame?userId="+this.userId;
      } else {
         url = "ws://"+this.$config.websocketurl+"/pveGame?userId="+this.userId;
      }
      console.log(url);
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websockSendMessage(e){
      //测试
      this.websock.send("helllo?");
    },
    websocketonopen: function () {
      console.log("WebSocket连接成功");
    },
    websocketonerror: function (e) {
      console.log("WebSocket连接发生错误");
    },
    //接受服务端返回数据
    websocketonmessage: function (e) {

      let parse = JSON.parse(e.data);
      //判断有没有获胜
      if(parse.winnerUserId>0||parse.winnerUserId<-1){
        this.$message.success("你赢啦！！！！！")
        this.over=true;
        //如果登陆保存战绩
        if(this.userId>0){
          this.$ajax.post(this.$config.url +`/game/saveGameScore`,{
            personId: this.userId,
            gameName: "五子棋",
            score: 1,
          }).then(() => {
            this.update();
          }).catch(() => {});
        }
        document.getElementById("canvas").onmousedown=false
      }
      if(parse.winnerUserId===-1){
        this.$message.success("你输啦！！！！！")
        this.over=true;
        if(this.userId>0){
          this.$ajax.post(this.$config.url +`/game/saveGameScore`,{
            personId: this.userId,
            gameName: "五子棋",
            score: -1,
          }).then(() => {
            this.update();
          }).catch(() => {});
        }
        document.getElementById("canvas").onmousedown=false
      }
      this.chessBoard[parse.y][parse.x] = 1;
      this.oneStep(parse.x,parse.y,parse.color)
    },
    websocketclose: function (e) {
      this.websock.close();
    },
    update() {
      this.$refs.lea.updateLeader();
    }
  },
  mounted() {
    this.initDraw();
  },
  created() {
    this.socketInit();
  },
  destroyed: function () {
    if(!this.over){
      this.$message.info("您逃跑啦！")
    }
    this.websock.close();
  }

};
</script>

<style scoped lang="less">

.Diary {
  box-sizing: border-box;
  max-width: 1360px;
  width: 100%;
  padding: 80px 50px;
  margin: 0 auto;
  .diary-main {
    box-sizing: border-box;
    width: 100%;
    padding: 30px 8% 30px 20%;
    //background-color: rgba(255, 255, 21, 1);
    border-radius: 15px;
    .el-timeline {
      /deep/ .el-timeline-item__timestamp {
        position: absolute;
        top: -8px;
        left: -134px;
        font-size: 20px;
        font-weight: bolder;
        color: #6bc30d;
      }
      .el-timeline-item {
        .el-card {
          pre {
            font-size: 14px;
            line-height: 30px;
          }
        }
      }
    }
  }
}
#screen {
  font-size: 22px;
  text-align: center;
  background-color: rgba(255,255,255,0);
  color: yellow;
  margin-bottom: 20px;
}
</style>